/**
 * 现代化加载管理系统
 */
class LoadingManager {
    constructor() {
        this.overlay = null;
        this.activeLoaders = new Set();
        this.init();
    }
    
    init() {
        // 创建全局加载遮罩
        this.overlay = document.createElement('div');
        this.overlay.className = 'loading-overlay';
        this.overlay.innerHTML = `
            <div class="loading-spinner">
                <div class="spinner"></div>
                <div class="loading-text">
                    <span class="loading-message">加载中</span>
                    <span class="loading-dots"></span>
                </div>
            </div>
        `;
        document.body.appendChild(this.overlay);
    }
    
    /**
     * 显示全局加载
     */
    show(message = '加载中') {
        const messageEl = this.overlay.querySelector('.loading-message');
        if (messageEl) {
            messageEl.textContent = message;
        }
        this.overlay.classList.add('show');
        document.body.style.overflow = 'hidden';
    }
    
    /**
     * 隐藏全局加载
     */
    hide() {
        this.overlay.classList.remove('show');
        document.body.style.overflow = '';
    }
    
    /**
     * 设置按钮加载状态
     */
    setButtonLoading(button, loading = true) {
        if (typeof button === 'string') {
            button = document.getElementById(button) || document.querySelector(button);
        }
        
        if (!button) return;
        
        if (loading) {
            button.classList.add('loading');
            button.disabled = true;
            this.activeLoaders.add(button);
        } else {
            button.classList.remove('loading');
            button.disabled = false;
            this.activeLoaders.delete(button);
        }
    }
    
    /**
     * 设置表格加载状态
     */
    setTableLoading(table, loading = true) {
        if (typeof table === 'string') {
            table = document.getElementById(table) || document.querySelector(table);
        }
        
        if (!table) return;
        
        if (loading) {
            table.classList.add('table-loading');
        } else {
            table.classList.remove('table-loading');
        }
    }
    
    /**
     * 创建骨架屏
     */
    createSkeleton(container, config = {}) {
        const defaultConfig = {
            lines: 3,
            avatar: false,
            button: false,
            ...config
        };
        
        let html = '';
        
        if (defaultConfig.avatar) {
            html += '<div class="skeleton skeleton-avatar"></div>';
        }
        
        for (let i = 0; i < defaultConfig.lines; i++) {
            const width = i === defaultConfig.lines - 1 ? 'short' : 
                         i === 0 ? 'long' : 'medium';
            html += `<div class="skeleton skeleton-text ${width}"></div>`;
        }
        
        if (defaultConfig.button) {
            html += '<div class="skeleton skeleton-button"></div>';
        }
        
        if (typeof container === 'string') {
            container = document.getElementById(container) || document.querySelector(container);
        }
        
        if (container) {
            container.innerHTML = html;
        }
        
        return html;
    }
    
    /**
     * 创建进度条
     */
    createProgressBar(container, progress = 0) {
        const progressHtml = `
            <div class="progress-bar">
                <div class="progress-fill" style="width: ${progress}%"></div>
            </div>
        `;
        
        if (typeof container === 'string') {
            container = document.getElementById(container) || document.querySelector(container);
        }
        
        if (container) {
            container.innerHTML = progressHtml;
            return container.querySelector('.progress-fill');
        }
        
        return null;
    }
    
    /**
     * 更新进度条
     */
    updateProgress(progressBar, progress) {
        if (typeof progressBar === 'string') {
            progressBar = document.querySelector(progressBar);
        }
        
        if (progressBar) {
            progressBar.style.width = `${Math.max(0, Math.min(100, progress))}%`;
        }
    }
    
    /**
     * 清除所有加载状态
     */
    clearAll() {
        this.hide();
        
        // 清除按钮加载状态
        this.activeLoaders.forEach(button => {
            this.setButtonLoading(button, false);
        });
        
        // 清除表格加载状态
        document.querySelectorAll('.table-loading').forEach(table => {
            table.classList.remove('table-loading');
        });
    }
    
    /**
     * 模拟加载进度
     */
    simulateProgress(progressBar, duration = 3000, callback = null) {
        let progress = 0;
        const increment = 100 / (duration / 50);
        
        const timer = setInterval(() => {
            progress += increment;
            this.updateProgress(progressBar, progress);
            
            if (progress >= 100) {
                clearInterval(timer);
                if (callback) callback();
            }
        }, 50);
        
        return timer;
    }
}

// 创建全局实例
window.Loading = new LoadingManager();

// 兼容旧的 setLoading 函数
window.setLoading = function(element, loading = true) {
    if (element && element.tagName === 'BUTTON') {
        window.Loading.setButtonLoading(element, loading);
    } else if (element && element.tagName === 'TABLE') {
        window.Loading.setTableLoading(element, loading);
    } else {
        // 通用处理
        if (loading) {
            element.classList.add('loading');
            element.disabled = true;
        } else {
            element.classList.remove('loading');
            element.disabled = false;
        }
    }
};

// 快捷方法
window.showLoading = (message) => window.Loading.show(message);
window.hideLoading = () => window.Loading.hide();
window.setButtonLoading = (button, loading) => window.Loading.setButtonLoading(button, loading);
window.setTableLoading = (table, loading) => window.Loading.setTableLoading(table, loading);